/*
 * Part of the NXT bluetooth remote control J2ME applet.
 * Copyright (C) 2007-2008 Alexander Demin, <alexander@demin.ws>
 *
 * This file is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You can redistribute this file and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software Foundation;
 * either version 2 of the License, or (at your discretion) any later version.
 * See the accompanying file "COPYING.txt" for more details.
 */
import java.io.*;
import java.util.*;

public class NxtReaderThread extends Thread {

   InputStream is;
   OutputStream os;

   Vector queue;

   boolean terminated;

   NxtMidlet.Logger logger;

   NxtReaderThread( NxtMidlet.Logger aLogger, InputStream inputStream, OutputStream outputStream ) {
      is = inputStream;
      os = outputStream;
      logger = aLogger;
   }

   public synchronized Vector getMessages() {
      Vector messages = (Vector)queue.clone();

      queue.clear();

      return messages;
   }

   public synchronized int getInAvail() { return queue.size(); }

   public void run() {

      queue = new Vector();

      try {

         int state = 0;

         byte[] prolog = new byte[2];
         int size = 0;

         terminated = false;

         while( !terminated ) {

            try {
               sleep(1);
            } catch( java.lang.InterruptedException e ) {}


            if( state == 0 ) {
               if( is.available() < 2 ) continue;

               is.read( prolog, 0, 2 );
               size = prolog[1] * 256 + prolog[0];

               state = 1;

            } else {
               
               if( is.available() < size ) continue;

               byte[] cmd = new byte[size];

               is.read( cmd, 0, size );

               state = 0;

               try {
                  NxtMessage message = new NxtMessage(cmd);

                  synchronized(this) {
                     queue.addElement( message );
                  }

                  if( message.getResponseNeeded() )
                     os.write( NxtMessage.RESPONSE_MSG );

               } catch( NxtMessage.UnknownMessage e ) {
               }

            }
         }

      } catch( java.io.IOException e ) {}
   }

   synchronized public void terminate() {
      terminated = true;
   }
}
